<template>
  <div class="drug-admin" style="padding:0px 10px 10px 40px;width:88%">
    <div style="display:flex;a-center;width:100%">
      <div>
        <div
          v-for="(item, index) in menuList"
          :key="index"
          style="position:relative;padding:10px 20px;color:#444;font-size:13px;width:100px;overflow:hidden"
          class="menu pointer"
          @click="changeMenu(item,index)"
        >
          <div
            style="width:3px;height:20px;position:absolute;left:0;top:50%;transform:translate(0,-50%)"
            :class="currentIndex == index ? 'main-bg-color' : 'pageff'"
          ></div>
          <div :class="currentIndex == index ? 'changecolor item' : 'item'">{{item.typeName}}</div>
        </div>
      </div>
      <div class="span-18 ml-1">
        <div class="d-flex a-center j-sb box-header">
          <div>
            <!-- <el-select v-model="sort" placeholder="排序方式">
              <el-option
                v-for="item in sortList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select> -->
            <el-input
              style="width:180px;margin-left:10px"
              placeholder="药品名称搜索"
              v-model="filter.name"
            ></el-input>
            <el-button type="primary" style="margin:0 10px" @click="searchData">查询</el-button>
            <el-button type="primary" @click="filterData(0)">全部</el-button>
            <el-button type="primary" @click="filterData(1)">出售中</el-button>
            <el-button type="primary" @click="filterData(2)">未上架</el-button>
            <el-button type="primary" @click="filterData(3)">已售罄</el-button>
          </div>
          <div>
            <el-button type="success" @click="exportData">导出</el-button>
            <el-button type="success" @click="addMedical">增加药品</el-button>
          </div>
        </div>

        <div class="mt-2">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            highlight-current-row
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
            @selection-change="selectionChange"
          >
            <el-table-column type="selection" min-width="5" align="center"></el-table-column>
            <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
            <el-table-column prop="medicalName" min-width="10" label="药品通用名" align="center"></el-table-column>
            <el-table-column prop="gbCode" min-width="10" label="国标" align="center"></el-table-column>
            <el-table-column prop="medicalSpecifications" min-width="5" label="规格" align="center"></el-table-column>
            <el-table-column prop="medicalDosageForm" min-width="5" label="剂型" align="center"></el-table-column>
            <el-table-column prop="medicalUnit" min-width="12" label="单位" align="center"></el-table-column>
            <el-table-column prop="medicalManufacturers" min-width="12" label="生产厂家" align="center"></el-table-column>
            <el-table-column prop="medicalActivePrice" min-width="5" label="售价(元)" align="center"></el-table-column>
            <el-table-column prop="stock" min-width="5" label="库存" align="center"></el-table-column>
            <el-table-column prop="medicalPrice" min-width="8" label="药品原价(元)" align="center"></el-table-column>
            <el-table-column min-width="8" label="药品状态" align="center">
              <template slot-scope="scope">
                <span>{{getStatus(scope.row.isOnline)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="300" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="amendData(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="deleteData(scope.row)">删除</el-button>
                <el-button
                  size="mini"
                  type="warning"
                  v-if="scope.row.isOnline==1"
                  @click="soldOut(scope.row)"
                >下架</el-button>
                <el-button size="mini" type="success" v-else @click="soldOut(scope.row)">上架</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="float: right;padding:5px;margin-top:10px;"
            small
            @current-change="currentChange"
            :current-page="currentPage"
            :pageSize="pageSize"
            layout="total, prev, pager, next"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      :title="visibleTitle"
      :visible.sync="dialogFormVisible"
      width="70%"
      top="10px"
      @close="closeDialog"
    >
      <el-form
        label-width="120px"
        :model="formData"
        :inline="true"
        ref="drugForm"
        :rules="rules"
        style="background:#f9f9f9;padding:20px;border-radius:5px;margin-bottom:20px"
      >
        <div>
          <el-form-item label="国标：" prop="gbCode">
            <el-input placeholder="请输入国标" v-model="formData.gbCode"></el-input>
          </el-form-item>
          <el-form-item label="药品通用名：" prop="medicalName">
            <el-input placeholder="请输入药品通用名" style="width:250px" v-model="formData.medicalName"></el-input>
          </el-form-item>
          <el-form-item v-if="menuList.length" label="药品分类：" prop="typeList" style="width:100%">
            <el-checkbox-group v-model="formData.typeList" style="width:100%;marginLeft:30px">
              <el-checkbox
                v-for="(checkItem, checkIndex) in menuList"
                :value="checkItem.id"
                :label="checkItem.id"
                :key="checkIndex"
              >{{checkItem.typeName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="生产厂家：" prop="medicalManufacturers">
            <el-input
              placeholder="请输入生产厂家"
              style="width:265px"
              v-model="formData.medicalManufacturers"
            ></el-input>
          </el-form-item>
          <el-form-item label="药品规格：" prop="medicalSpecifications">
            <el-input placeholder="请输入药品规格" v-model="formData.medicalSpecifications"></el-input>
          </el-form-item>
          <el-form-item label="剂型：" prop="medicalDosageForm">
            <el-input placeholder="如“颗粒”，“乳膏”" v-model="formData.medicalDosageForm"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="药品单位：" prop="medicalUnit">
            <el-input placeholder="请输入单位名称" v-model="formData.medicalUnit"></el-input>
          </el-form-item>
          <el-form-item label="OTC药品：" prop="isOTC">
            <el-radio v-model="formData.isOTC" label="1">是</el-radio>
            <el-radio v-model="formData.isOTC" label="2">否</el-radio>
          </el-form-item>
          <el-form-item label="立即上架：" style="margin-left:30px">
            <el-switch
              v-model="formData.isOnline"
              active-color="#13ce66"
              inactive-color="#cccccc"
              active-value="1"
              inactive-value="2"
              @change="onChange"
            ></el-switch>
          </el-form-item>
        </div>
        <el-form-item label="药品图片：" prop="medicalImg">
          <el-upload
            class="avatar-uploader"
            :action="imgUpload"
            list-type="picture-card"
            :file-list="formData.imgList"
            :on-success="medicalImgUpload"
            :on-remove="medicalImgRemove"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <div>
          <el-form-item label="药品说明书：" prop="desc">
            <z-editor :id="tinymce" :tinymceHtml="formData.desc" ref="editorHtml"></z-editor>
          </el-form-item>
        </div>
        <div class="d-flex">
          <div style="width:120px;text-align:right;">价格库存：</div>
          <div
            style="width:70%;background:#f0f0f0;padding:10px;border-radius:5px;margin-bottom:20px"
          >
            <el-form-item label="售价：" prop="medicalActivePrice">
              <el-input placeholder v-model="formData.medicalActivePrice" style="width:150px">
                <template slot="prepend">￥</template>
              </el-input>
            </el-form-item>
            <el-form-item label="划线价：" prop="medicalPrice">
              <el-input placeholder v-model="formData.medicalPrice" style="width:150px">
                <template slot="prepend">￥</template>
              </el-input>
            </el-form-item>
            <el-form-item label="库存：" prop="stock">
              <el-input placeholder="请输入库存" v-model="formData.stock"></el-input>
            </el-form-item>
            <div>
              <el-form-item label="库存：" prop="isShowStock">
                <el-checkbox v-model="formData.isShowStock">商品详情显示库存</el-checkbox>
                <p class="text-color-888 font-ssm">库存为0时,会放到[已售罄]的商品列表里,保存后卖家看到的商品可售库存同步更新</p>
              </el-form-item>
              <el-form-item label="库存扣减方式：">
                <div>
                  <el-radio v-model="formData.stockType" label="1">拍下减库存</el-radio>
                  <p class="text-color-888 font-ssm">买家提交订单,扣减库存数量,可能存在恶意占用库存风险</p>
                </div>
                <div>
                  <el-radio v-model="formData.stockType" label="2">付款减库存</el-radio>
                  <p class="text-color-888 font-ssm">买家支付成功,扣减库存数量,可能存在超卖风险。你已设置超卖订单自动退款</p>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>

      <div slot="footer" class="text-center">
        <el-button style="margin-right:20px" @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisibleTrue">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import JSZip from "jszip";
import Editor from "@/components/Editor";
import tinymce from "tinymce/tinymce";
export default {
  components: {
    "z-editor": Editor
  },
  data() {
    const imgRule = (rule, value, callBack) => {
      if (!this.formData.imgList || !this.formData.imgList.length) {
        return callBack(new Error("请上传药品图片"));
      } else {
        return callBack();
      }
    };
    const priceRule = (rule, value, callBack) => {
        if(value==''||value==undefined||value==null) {
             return callBack(new Error('请输入售价'))
        }else {
            if(isNaN(Number(value))) {
                return callBack(new Error('请输入数字'))
            }else{
                if(value < 0) {
                    return callBack(new Error('不能小于0'))
                }else {
                    return callBack()
                }
            }
        }
    };
    const medicalPriceRule = (rule, value, callBack) => {
        if(value==''||value==undefined||value==null) {
             return callBack(new Error('请输入划线价'))
        }else {
            if(isNaN(Number(value))) {
                return callBack(new Error('请输入数字'))
            }else{
                if(value < 0) {
                    return callBack(new Error('不能小于0'))
                }else {
                    return callBack()
                }
            }
        }

    };
    return {
      menuList: [],
      currentIndex: 0,
      tableData: [],
      sort: "",
      sortList: [
        { title: "按创建日期先后", id: 1 },
        { title: "开通人数由高到低", id: 2 },
        { title: "参保人数由高到低", id: 3 }
      ],
      filter: {},
      selectionData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      visibleTitle: "新增",
      formData: {
        imgList: [],
        isOnline: "1",
        isShowStock: false,
        desc: "",
        typeList: [],
        stockType: "2"
      },
      tinymce: "tinymce",
      typeName: null,
      rules: {
        gbCode: [
          { required: true, message: "请输入国标", trigger: "blur" }
        ],
        medicalName: [
          { required: true, message: "药品通用名", trigger: "blur" }
        ],
        typeList: [
          { required: true, message: "请选择药品分类", trigger: "blur" }
        ],
        medicalManufacturers: [
          { required: true, message: "请输入生产厂家", trigger: "blur" }
        ],
        medicalSpecifications: [
          { required: true, message: "请输入药品规格", trigger: "blur" }
        ],
        medicalDosageForm: [
          { required: true, message: "请输入剂型", trigger: "blur" }
        ],
        medicalUnit: [
          { required: true, message: "请输入单位名称", trigger: "blur" }
        ],
        isOTC: [{ required: true, message: "是否是OTC药品", trigger: "blur" }],
        medicalImg: [{ validator: imgRule }],
        desc: [{ required: true, message: "请输入药品说明", trigger: "blur" }],
        medicalActivePrice: [
          { required: true, message: "请输入售价", trigger: "blur" },{ validator:priceRule }
        ],
        medicalPrice: [
          { required: true,message: "请输入划线价", trigger: "blur" },{validator:medicalPriceRule}
        ],
        stock: [{ required: true,message: "请输入库存", trigger: "blur" }],
      }
    };
  },
  methods: {
    changeMenu(item, index) {
      if (this.currentIndex != index) {
        this.currentPage = 1;
        this.currentIndex = index;
        this.typeName = item.typeName;
        this.filter={}
        this.selectMedicalPage();
      }
    },
    selectMedicalPage() {
      this.post(
        "/medicalAdministration/selectMedicalPage",
        {
          typeName: this.typeName,
          pageSize: this.pageSize,
          pageNum: this.currentPage,
          medicalName:this.filter.name,
          isOnline:this.filter.isOnline,
          stock:this.filter.stock,
          sellOut:this.filter.sellOut
        },
        res => {
          this.tableData = res.data.list;
          this.total = res.data.total;
        },
        false
      );
    },
    //搜索按钮
    searchData() {
        this.filter={name:this.filter.name}
        this.selectMedicalPage()
    },
    //搜索过滤
    filterData(num) {
        switch(num){
            case 0 :
                this.filter={}
                this.selectMedicalPage()
            break;
            case 1 :
                this.filter={isOnline:1,name:this.filter.name}
                this.selectMedicalPage()
            break;
            case 2 :
                this.filter={isOnline:2,name:this.filter.name}
                this.selectMedicalPage()
            break;
            case 3 :
                this.filter={sellOut:'a',name:this.filter.name}
                this.selectMedicalPage()
            break;
        }
    },
    closeDialog() {
      this.formData = {
        imgList: [],
        isOnline: "2",
        isShowStock: false,
        desc: "",
        typeList: [],
        stockType: "2"
      };
    },
    exportData() {
      if (this.selectionData && this.selectionData.length) {
        this.handleBatchDownload();
      } else {
        this.$message.warning("请选择需要导出的列表项");
      }
    },
    handleBatchDownload() {
      this.excelReferral(); //导出excel
    },
    excelReferral() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/vendor/Export2Excel");
        const tHeader = [
          "药品通用名",
          "国标",
          "规格",
          "剂型",
          "单位",
          "厂家",
          "库存",
          "药品原价(元)",
          "药品状态"
        ];
        const filterVal = [
          "medicalName",
          "gbCode",
          "medicalSpecifications",
          "medicalDosageForm",
          "medicalUnit",
          "medicalManufacturers",
          "stock",
          "medicalPrice",
          "isOnline"
        ];
        let tmplist = [];
        this.selectionData.forEach(obj => {
          let item = Object.assign({}, obj);
          item.isOnline = this.getStatus(item.isOnline);
          tmplist.push(item);
        });
        const list = tmplist;
        const timeFormat = this.$moment(new Date()).format("YYYYMMDDHHmmss");
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(
          tHeader,
          data,
          this.menuList[this.currentIndex].name + timeFormat
        );
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    medicalImgUpload(file) {
      this.formData.imgList.push({imgUrl:file.data.original});
      console.log(this.formData.imgList)
    },
    medicalImgRemove(file) {
      this.formData.imgList.splice(this.formData.img.indexOf(file), 1);
    },
    getStatus(isOnline) {
      if (isOnline == 1) {
        return "上架中";
      } else {
        return "已下架";
      }
    },
    //新增药或修改
    dialogFormVisibleTrue() {
      this.getTinymceHtml();
      this.$refs["drugForm"].validate(valid => {
        if (valid) {
          const param = this.deepClone(this.formData);
          param.isShowStock = param.isShowStock ? "1" : "2";
          let imgs = [];
          param.imgList.map(e => {
            imgs.push(e.imgUrl);
          });
          param.imgList = imgs;
          param.imgList = param.imgList.join();
          param.typeList = param.typeList.join();
          if (this.visibleTitle == "新增") {
            this.post("/medicalAdministration/addMedical", param, res => {
              if (res.code == 200) {
                this.dialogFormVisible = false;
                this.closeDialog();
                this.$message.success("新增成功");
                this.selectMedicalPage();
              } else {
                this.$message.error("新增失败");
              }
            },false);
          } else {
            this.post(
              "/medicalAdministration/updateMedical",
              param,
              res => {
                if (res.code == 200) {
                  this.dialogFormVisible = false;
                  this.closeDialog();
                  this.$message.success("修改成功");
                  this.selectMedicalPage();
                } else {
                  this.$message.error("修改失败");
                }
              },
              false
            );
          }
        } else {
          return false;
        }
      });
    },
    currentChange(val) {
      this.currentPage = val;
      this.selectMedicalPage();
    },
    selectionChange(val) {
      this.selectionData = val;
    },
    addMedical() {
      this.visibleTitle = "新增";
      this.dialogFormVisible = true;
    },
    amendData(row) {
      let list = [];
      row.typeList.map(e => {
        list.push(e.medicalTypeId);
      });
      row.typeList = list;
      this.formData = row;
      this.formData.isShowStock =
        this.formData.isShowStock == "1" ? true : false;
      this.visibleTitle = "编辑";
      this.dialogFormVisible = true;
    },
    //删除商品
    deleteData(row) {
      this.$confirm("确认删除？")
        .then(_ => {
          this.post(
            "/medicalAdministration/delete",
            { id: row.id },
            res => {
              if (res.code == 200) {
                this.selectMedicalPage();
                this.$message.success("删除成功");
              }
            },
            false
          );
        })
        .catch(_ => {
          console.log(22);
        });
    },
    onChange(e) {
      this.post(
        "/medicalAdministration/isOnline",
        { id: this.formData.id, isOnline: this.formData.e },
        res => {
          if (res.code == 200) {
            this.$message.success("修改成功");
          }
        },
        false
      );
    },
    //下架商品
    soldOut(row) {
      if (row.isOnline == 2) {
        row.isOnline = "1";
      } else {
        row.isOnline = "2";
      }
      this.post(
        "/medicalAdministration/isOnline",
        { id: row.id, isOnline: row.isOnline },
        res => {
          if (res.code == 200) {
            this.selectMedicalPage();
            this.$message.success("修改成功");
          }
        },
        false
      );
    },
    getTinymceHtml() {
      const content = tinymce.editors["tinymce"].getContent();
      this.formData.desc = content;
    },
    getMenuList() {
      this.post(
        "/medicalAdministration/selectDrugType",
        {},
        res => {
          if (
            sessionStorage.getItem("userId") == 1 ||
            sessionStorage.getItem("userId") == 3
          ) {
            this.menuList = res.data;
            this.typeName = res.data[0].typeName;
            this.selectMedicalPage();
          } else {
            this.menuList = res.data[0].concat(res.data[1]);
            this.typeName = res.data[0].typeName;
            this.selectMedicalPage();
          }
        },
        false
      );
    }
  },
  mounted() {
    this.getMenuList();
  }
};
</script>

<style scoped>
.drug-admin .menu .item {
  color: #444;
}
.drug-admin .menu .item:hover {
  color: #0882f4;
}
.drug-admin .menu .changecolor {
  color: #0882f4;
}
</style>